package com.gonsin.ta.logic.parse.condition.context;

import com.gonsin.ta.logic.TA;
import org.springframework.context.ApplicationContext;

import java.io.Serializable;
import java.util.Map;

/**
 * 在groovy中的代理，为防止groovy shell多次启动，加快groovy执行效率，采用ThreadHolder的方式，存储实际的ChainContext供groovy中使用
 */
public class ChainContextGroovyProxy implements ChainContext {

    private ApplicationContext applicationContext;

    private ThreadLocal<ChainContextImpl> contextLocal;

    public ChainContextGroovyProxy(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        this.contextLocal = new ThreadLocal<>();
    }

    @Override
    public void endChain() {
        contextLocal.get().endChain();
    }

    @Override
    public String getInstanceId() {
        return contextLocal.get().getInstanceId();
    }

    @Override
    public String getChainId() {
        return contextLocal.get().getInstanceId();
    }

    @Override
    public <T> T getValue(String key) {
        return contextLocal.get().getValue(key);
    }

    @Override
    public void putValue(String key, Serializable value) {
        contextLocal.get().putValue(key, value);

    }

    @Override
    public void setValues(Map<String, Serializable> values) {
        contextLocal.get().setValues(values);

    }

    @Override
    public Map<String, Object> getValues() {
        return contextLocal.get().getValues();
    }

    @Override
    public Object getBean(String beanName) {
        if("log".equals(beanName)){
            return TA.log();
        }
        return applicationContext.getBean(beanName);
    }

    @Override
    public Object getBean(Class beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public void setContextLocal(ChainContextImpl context) {
        contextLocal.set(context);
    }


    public ChainContextImpl getContext(){
        return contextLocal.get();
    }
}
